package com.longrise.android.byjk.plugins.aboutme.personalInfo.change;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalInfoActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalPresenter;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.datasource.remote.LoadDataManager;

/**
 * Created by sujizhong on 2017/2/10.
 * 绑定手机号 提示界面
 */

public class BundlePhoneActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "BundlePhoneActivity";

    private final String SAVE_IS_CHANGE = "SAVE_IS_CHANGE";
    public static final String EXTRA_IS_FROM = "EXTRA_IS_FROM";

    private Toolbar mTitle;

    private ImageView mIVPhoneIcon;
    private TextView mTVPhone;
    private TextView mTVZH;
    private TextView mTVChange;
    private TextView mTVRunLogin;
    private TextView mTVPhoneno;
    private TextView mTVAccount;

    private View mLoading;

    private boolean mIsChange = false;
    private boolean mIsFromSecurity = false;  //是否在账号与安全也进入

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mIsChange = savedInstanceState.getBoolean(SAVE_IS_CHANGE);
            mIsFromSecurity = savedInstanceState.getBoolean(EXTRA_IS_FROM);
        }
        return R.layout.activity_bundlephone;
    }


    @Override
    public void initView() {
        mIVPhoneIcon = (ImageView) findViewById(R.id.iv_bp_phoneicon);
        mTVPhone = (TextView) findViewById(R.id.tv_bp_sign);
        mTVZH = (TextView) findViewById(R.id.tv_bp_zh);
        mTVChange = (TextView) findViewById(R.id.tv_bp_change);
        mTVRunLogin = (TextView) findViewById(R.id.tv_runlogin_bundle);
        mTVPhoneno = (TextView) findViewById(R.id.tv_bp_phoneno);
        mTVAccount = (TextView) findViewById(R.id.tv_bp_account);

        mLoading = findViewById(R.id.rela_load_xqpc);
        showLoading(false);

        getExtraData();
        initTitle();
        onEvent();
        setData();

    }

    private void getExtraData() {
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra(EXTRA_IS_FROM)) {
            mIsFromSecurity = intent.getBooleanExtra(EXTRA_IS_FROM, false);
        }
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.title_bundlephone));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                close();
            }
        });
    }

    private void onEvent() {
        mTVChange.setOnClickListener(this);
    }

    private void showLoading(boolean isLoading) {
        mLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    private void setData() {
        String phone = UserInfor.getInstance().getUserphone();
        String sfzh = UserInfor.getInstance().getUsersfzh();
//        String yhzh = getString(R.string.userzh) + "：";
        mTVAccount.setText(TextUtils.isEmpty(sfzh) ? UserInfor.getInstance().getUserName() : sfzh);
        if (TextUtils.isEmpty(phone)) {
//            mIVPhoneIcon.setImageResource(R.drawable.nobundleiv);
            mTVPhone.setText(getString(R.string.bundle_phone_hint));
            mTVChange.setText(getString(R.string.bundlephone));

//            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mTVZH.getLayoutParams();
//            lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        } else {
//            mIVPhoneIcon.setImageResource(R.drawable.bundleiv);
            mTVPhone.setText(getString(R.string.bundlephone));
            mTVPhoneno.setText(phone);
            mTVChange.setText(getString(R.string.changephone));

//            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mTVZH.getLayoutParams();
//            lp.addRule(RelativeLayout.ALIGN_LEFT, R.id.tv_bp_phoneno);
        }
        String runLogin = UserInfor.getInstance().getIsopenmobilelogin();
//        if (runLogin != null && runLogin.equals("1")) {
//            mTVRunLogin.setText(R.string.openmoblicloginsuccess);
//            mTVRunLogin.setVisibility(View.VISIBLE);
//        } else {
//            mTVRunLogin.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_bp_change:
//                if (checkSFZH()) {
//                    openChangeAct();
//                } else {
//
//                }
                requestCheckSFZH(); //直接请求，避免同一账号多终端在线操作误差
                break;
        }
    }

    /**
     * 修改手机号时，判断是否已经完善个人资料
     */
    private boolean checkSFZH() {
        String sfzh = UserInfor.getInstance().getUsersfzh();  //身份证号
        boolean isNullSFZH = TextUtils.isEmpty(sfzh); //身份证号是否为null or ""
        String isRealCardNo = UserInfor.getInstance().getIsRealCardNo();
        boolean isRealNo = isRealCardNo != null && isRealCardNo.equals("1");  //是否是身份证号
        if (!isNullSFZH && isRealNo) {
            return true;
        }
        return false;
    }

    private void requestCheckSFZH() {
        mTVChange.setClickable(false);
        showLoading(true);
        EntityBean bean = new EntityBean();
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        commit("bbt_user_isAbleToModifyMobile", reqBean);
    }

    private void commit(String api, EntityBean bean) {
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, api, bean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean resultBean = (EntityBean) result;
                    parseCheckSFZH(resultBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                showToast(getString(R.string.nonetwork));
            }

            @Override
            public void onFinished(String key, String service) {
                mTVChange.setClickable(true);
                showLoading(false);
            }
        });
    }

    private void parseCheckSFZH(EntityBean resultBean) {
        int resultState = resultBean.getInt("resultstate");
        if (resultState == 1) {
            EntityBean isabletomodifyBean = resultBean.getBean("result");
            String isabletomodify = isabletomodifyBean.getString("isabletomodify");
            String isopenmobilelogin = UserInfor.getInstance().getIsopenmobilelogin();
            String personname = UserInfor.getInstance().getPersonname();

            if ("1".equals(isopenmobilelogin)) { //已开通
                if (TextUtils.isEmpty(personname) || isabletomodify.equals("0")) {
                    showCompleteData();
                } else {
                    openChangeAct();
                }
            } else {
                openChangeAct();
            }


//            if (isabletomodify != null && isabletomodify.equals("1")) {
//                openChangeAct();
//            } else {
//                showCompleteData();
////                showToast(resultBean.getString("resultdesc"));
//            }
//        } else {
//            showToast(resultBean.getString("resultdesc"));
        }
    }

    private void openChangeAct() {
        if (TextUtils.isEmpty(UserInfor.getInstance().getUserphone())) {
            Intent intent = new Intent(this, ChangeInfoActivity.class);
            intent.putExtra("type", PersonalPresenter.CHANGEPHONENUMBER);
            startActivityForResult(intent, 100);
        } else {
            Intent intent = new Intent(this, ChangePhoneActivity.class);
            startActivityForResult(intent, 100);
        }
    }

    private void showCompleteData() {
        View completeDataView = View.inflate(this, R.layout.dialog_completedata, null);
        TextView hint = (TextView) completeDataView.findViewById(R.id.tv_content_completedata);
        hint.setText("请先完善姓名和身份证号");
        hint.setTextColor(Color.parseColor("#ff9900"));
        TextView dialogCancle = (TextView) completeDataView.findViewById(R.id.tv_cancle_completedata);
        dialogCancle.setText("以后再说");
        TextView dialogConfirm = (TextView) completeDataView.findViewById(R.id.tv_confrim_completedata);
        dialogConfirm.setText("立即完善");
        final View.OnClickListener completeListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
                if (v.getId() == R.id.tv_confrim_completedata) {
                    if (mIsFromSecurity) { //从账号与安全页进入 打开个人资料页
                        startActivity(new Intent(BundlePhoneActivity.this, PersonalInfoActivity.class));
                    } else {
                        finish();  //从个人资料页进入 直接关闭该页面
                    }
                }
            }
        };
        dialogCancle.setOnClickListener(completeListener);
        dialogConfirm.setOnClickListener(completeListener);
        DialogUtil.getInstance().creatAlertDialog(this, completeDataView, 266, 171);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && data != null) {
            mIsChange = data.getBooleanExtra("key", false);
            if (mIsChange) {
                //绑定手机成功 提示框
                showToast(getString(R.string.bundlemobliesuccess));
//                    showPhoneSuccess();
                try {
                    setData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void close() {
        setResult(-10, new Intent().putExtra("key", mIsChange));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVE_IS_CHANGE, mIsChange);
        outState.putBoolean(EXTRA_IS_FROM, mIsFromSecurity);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
